package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获得request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获得访问路径
        String path = request.getURI().getPath();
        //2.判断是否登录
        if (path.contains("/login")){
            //是登录则放行
            return chain.filter(exchange);
        }
        //3.不是登录,则获取token
        String token = request.getHeaders().getFirst("token");
        //4.查看token是否存在
        if (StringUtils.isBlank(token)){
            //如果不存在则返回401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //断开连接
            return response.setComplete();
        }

        try {
            //5.如果存在,判断token是否有效
            //获取token Body
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            //解析token body
            int result = AppJwtUtil.verifyToken(claimsBody);
            //判断token是否过期,1 ,2 则代表过期
            if (result == 1 || result ==2){
                //如果过期了则返回401
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                //断开连接
                return response.setComplete();
            }
            //因为getClaimsBody可能会抛出异常所以要用try catch捕获一下.
        } catch (Exception e) {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //6.放行
        return chain.filter(exchange);
    }

    /*
        设置优先级,值越低,优先级越高
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
